<template>
  <div class="system-email-sender fit bg-white q-pa-md">
    <div class="row full-width">
      <q-btn
        class="send-btn"
        icon="send" color="primary"
        :loading="sending"
        @click="sendEmail"></q-btn>
    </div>
    <input-field
      :ref="`input_field_validator_${field.Name || field.Label}`"
      v-for="(field, idx) in fields" :key="idx"
      :Field="field" :values="data"></input-field>
  </div>
</template>

<script>
import mixins from 'eis-admin-mixins';

export default {
  name: 'CommitteeEmail',
  mixins: [mixins.InputFieldValidator],
  data() {
    return {
      fields: [
        {
          Type: 'String',
          Name: 'mid',
          Label: '收件人',
          Placeholder: '可选。收件人邮箱地址，多个用分号分割。不填写则发送给所有成员单位。',
        },
        {
          Type: 'String',
          Name: 'title',
          Label: '主题',
          Required: true,
        },
        {
          Type: 'Rich',
          Name: 'html',
          Label: '内容',
          Required: true,
          Warning: '可嵌入图片、视频、超级链接。较大图片或视频请使用超链接！',
          Options: {
            MaxLength: 1000000,
            MaxSize: '1000M',
            NoUpload: true,
          },
        },
      ],
      data: {
        mid: '',
        title: '',
        html: '',
      },
      sending: false,
    };
  },
  methods: {
    sendEmail() {
      const submitCall = () => {
        this.postRequest('/sdcomm/mgmt/email', this.data).then((d) => {
          if (d && d.msg === 'OK') {
            this.$q.notify(this.$t('notifySucceed'));
            this.data = {
              title: '',
              html: '',
            };

            const {
              sent,
              fail,
            } = d.data;

            this.showNotifyDialog({
              content: `发送成功${sent || 0}；发送失败${fail || 0}`,
              size: {
                w: 460,
              },
              okText: '确定',
            });
          } else {
            this.$q.notify(this.$t('notifySubmitFailed'));
          }
        }).then(() => {
          this.sending = false;
        }).catch(() => {
          this.sending = false;
        });
      };

      const submitFunc = () => {
        // submit
        this.showNotifyDialog({
          content: this.$t('请确发送'),
          warning: '群发邮件，耗时较长，请耐心等待',
          canCancel: true,
          size: {
            w: 460,
          },
          okText: '发送',
          cancelText: this.$t('cancelButtonText'),
        }, () => {
          this.sending = true;

          submitCall();
        });
      };

      // validate
      if (!this.validate()) {
        // jump to the failed field
        this.$nextTick(() => {
          const invalidF = document.querySelectorAll('.hasError');
          if (invalidF && invalidF.length > 0) {
            this.$q.notify(this.$t('inputValidateFailed'));
            const invalidFList = [].slice.call(invalidF);

            const theLastInvalidF = invalidFList.pop();
            theLastInvalidF.scrollIntoView({ block: 'center', behavior: 'smooth' });
          } else {
            submitFunc();
          }
        });
      } else {
        submitFunc();
      }
    },

    async showNotifyDialog(options, func, catchFunc) {
      if (!options) {
        return;
      }

      this.$MsgDialog({ type: '', ...options })
        .then(() => {
          if (func && typeof func === 'function') {
            func();
          }
        })
        .catch(() => {
          if (catchFunc && typeof catchFunc === 'function') {
            catchFunc();
          }
        });
    },
  },
};
</script>

<style lang="scss" scoped>
.system-email-sender {
  .send-btn {
    border-radius: 4px;
    margin-bottom: 10px;
  }

  :deep(.field-label) {
    min-width: 50px;
    width: 50px;
  }
}
</style>
